package com.gxuwz.attendance.dao;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import com.gxuwz.attendance.entity.Attendance;
import com.gxuwz.attendance.entity.Record;
import com.gxuwz.attendance.entity.Student;
import com.gxuwz.attendance.vo.Page;
import net.sf.json.JSONArray;

@Repository("AttendanceDao")
public class AttendanceDao extends SessionFactoryDao{

	
	/**
	 * 根据人数随机查询
	 * @param num
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Attendance> findByNum(Attendance attendance, String num){
		List<Student> list = new ArrayList<Student>();
		List<Attendance> attendances = new ArrayList<Attendance>();
		String hql = "";
		// 班级编号
		if(attendance.getClassNo() != null && !"".equals(attendance.getClassNo())) {
			
			hql = "From Student where  classNo='" + attendance.getClassNo() + "' order by rand()";
		}else {
			
			hql = "From Student order by rand()";
		}
		
		
		list = getSession().createQuery(hql).list();
		
		if(!list.isEmpty()) {
			if(Integer.parseInt(num) > list.size()) {
				list = list.subList(0, list.size());
			}else {
				list = list.subList(0, Integer.parseInt(num));
			}
			// 将学生信息赋值到考勤实体
			LocalDateTime date = LocalDateTime.now();
			String time = date + "";
			time = time.replace("T", " ").substring(0, time.length() - 7);
			for (Student s : list) {
				Attendance a = new Attendance();
				a.setClassNo(s.getClassNo());
				a.setStudentNo(s.getStudentNo());
				a.setStudentName(s.getStudentName());
				a.setCheckDate(time);
				
				attendances.add(a);
			}
			
			
		}else {
			return null;
		}
		
		return attendances;
	}
	
	/**
	 * 批量保存考勤记录
	 * @param data
	 */
	public boolean batchSave(String data) {
		boolean execute = true; // 是否保存成功标识
		JSONArray array = JSONArray.fromObject(data);
		Session session = null;
		try {
			session = getSession();
			// 开启事务
			session.beginTransaction();
			for (int i = 0; i < array.size(); i++) {
				Record record = new Record();
				
				String hql = "from Record  where studentNo = '" + array.getJSONObject(i).getString("studentNo") + "'";

				int late = 0;
				int early = 0;
				int normal = 0;
				int truancy = 0;
				int leave = 0;
				
				boolean flag = false;   // 保存和更新的标识
				
				if(getSession().createQuery(hql).list().isEmpty()) {
					record = new Record();
			
					flag = true;
				}else {
					record = (Record) getSession().createQuery(hql).list().get(0);
					late = record.getLate();
					early = record.getEarly();
					normal = record.getNormal();
					truancy = record.getTruancy();
					leave = record.getLeaved();
				}
				
				if(array.getJSONObject(i).getString("status").equals("0")) {
					normal = normal + 1;
				}else if(array.getJSONObject(i).getString("status").equals("1")) {
					truancy = truancy + 1;
				}else if(array.getJSONObject(i).getString("status").equals("2")) {
					late = late + 1;
				}else if(array.getJSONObject(i).getString("status").equals("3")) {
					leave = leave + 1;
				}else if(array.getJSONObject(i).getString("status").equals("4")) {
					early = early + 1;
				}
				
				record.setLate(late);
				record.setEarly(early);
				record.setNormal(normal);
				record.setTruancy(truancy);
				record.setLeaved(leave);
				record.setStudentNo(array.getJSONObject(i).getString("studentNo"));
				record.setClassNo(array.getJSONObject(i).getString("classNo"));
				record.setStudentName(array.getJSONObject(i).getString("studentName"));
				
				if(flag == true) {
					session.save(record);	
				}else {
					session.update(record);
				}
				
			}

			session.getTransaction().commit();
		}catch (Exception e) {
			execute = false;
			e.printStackTrace();
			session.getTransaction().rollback(); // 出错将回滚事物
		}finally {
			session.close();
		}
		return execute;
	}
	
	/**
	 * 分页查询考勤学生
	 * @param attendance
	 * @param page
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Attendance> findByPage(Attendance attendance, Page page){
		List<Student> list = new ArrayList<Student>();
		List<Attendance> attendances = new ArrayList<Attendance>();
		
		// 获取当前用户类型
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		String utype = (String) session.getAttribute("utype");
//		User currentUser  = (User) session.getAttribute("user");
		
		
		String hql = "";
		if(attendance.getStudentName() == null || "".equals(attendance.getStudentName())) {
			hql = "From Student where 1 = 1";
			// 当前用户类型是老师
			if(utype.equals("3")) {
				hql = "From Student where 1=1";
			}
		}else {
			hql = "From Student where studentName like '%" + attendance.getStudentName() + "%'";
			// 当前用户类型是老师
			if(utype.equals("3")) {
				
			}
		}
		// 班级编号
		if(attendance.getClassNo() != null && !"".equals(attendance.getClassNo())) {
			
			hql = hql + " and classNo='" + attendance.getClassNo() + "'";
		}
		list = getSession().createQuery(hql).list();
		// 存储本次查询的总记录数(人数)
		session.setAttribute("size", list.size());
		
		if(!list.isEmpty()) {
			// 分页
			if(page.getRows()*page.getPage() > list.size()) {
				list = list.subList(page.getOffset(), list.size());
			}else {
				list = list.subList(page.getOffset(), page.getRows()*page.getPage());
				
			}
			// 将学生信息赋值到考勤实体
			LocalDateTime date = LocalDateTime.now();
			String time = date + "";
			time = time.replace("T", " ").substring(0, time.length() - 7);
			for (Student s : list) {
				Attendance a = new Attendance();
				a.setClassNo(s.getClassNo());
				a.setStudentNo(s.getStudentNo());
				a.setStudentName(s.getStudentName());
				a.setCheckDate(time);
				
				attendances.add(a);
			}
			
		}else {
			return null;
		}
		
		return attendances;
	}
	
	
}
